package com.adtech.sys.birthcertificate.utils;


//import sun.misc.BASE64Decoder;
//import sun.misc.BASE64Encoder;
import java.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SM4Utils {
	private String secretKey = "";
	private String iv = "";
	private boolean hexString = false;
	private static String hexStrings = "0123456789ABCDEF";

	public String getSecretKey() {
		return secretKey;
	}

	public void setSecretKey(String secretKey) {
		this.secretKey = secretKey;
	}

	public boolean isHexString() {
		return hexString;
	}

	public void setHexString(boolean hexString) {
		this.hexString = hexString;
	}

	public SM4Utils() {
	}

	public String encryptData_ECB(String plainText) throws Exception {

			SM4_Context ctx = new SM4_Context();
			ctx.isPadding = true;
			ctx.mode = SM4.SM4_ENCRYPT;

			byte[] keyBytes;

			keyBytes = secretKey.getBytes();

			SM4 sm4 = new SM4();
			sm4.sm4_setkey_enc(ctx, keyBytes);
			byte[] encrypted = sm4
					.sm4_crypt_ecb(ctx, plainText.getBytes("GBK"));
			String cipherText = byteToHex(encrypted);
			// String cipherText = new BASE64Encoder().encode(encrypted);

			if (cipherText != null && cipherText.trim().length() > 0) {
				Pattern p = Pattern.compile("\\s*|\t|\r|\n");
				Matcher m = p.matcher(cipherText);
				cipherText = m.replaceAll("");
			}
			return cipherText;
		
	}

	public String byteToHex(byte[] data) {
		String hexString = "";
		for (int i = 0; i < data.length; i++) {
			String hex = Integer.toHexString(data[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			hexString += hex;
		}
		return hexString.toUpperCase();
	}

	public String decryptData_ECB(String cipherText) throws IOException, Exception {
		
			SM4_Context ctx = new SM4_Context();
			ctx.isPadding = true;
			ctx.mode = SM4.SM4_DECRYPT;

			byte[] keyBytes;

			keyBytes = secretKey.getBytes("GBK");

			SM4 sm4 = new SM4();
			sm4.sm4_setkey_dec(ctx, keyBytes);

			ByteArrayOutputStream baos = new ByteArrayOutputStream(
					cipherText.length() / 2);
			// 将每2位16进制整数组装成一个字节
			for (int i = 0; i < cipherText.length(); i += 2) {
				baos.write((hexStrings.indexOf(cipherText.charAt(i)) << 4 | hexStrings
						.indexOf(cipherText.charAt(i + 1))));
			}
			byte[] bytes = baos.toByteArray();

//			String str = new BASE64Encoder().encode(bytes);
			String str = Base64.getEncoder().encodeToString(bytes);
			byte[] decrypted = sm4.sm4_crypt_ecb(ctx,  Base64.getDecoder().decode(str));
			return new String(decrypted, "GBK");
		
	}

	public byte[] hexStringtobyt(String hexString) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream(
				hexString.length() / 2);
		// 将每2位16进制整数组装成一个字节
		for (int i = 0; i < hexString.length(); i += 2) {
			baos.write((hexString.indexOf(hexString.charAt(i)) << 4 | hexString
					.indexOf(hexString.charAt(i + 1))));
		}
		byte[] data = baos.toByteArray();
		baos.close();
		return data;
	}

	public String encryptData_CBC(String plainText) throws Exception {
	
			SM4_Context ctx = new SM4_Context();
			ctx.isPadding = true;
			ctx.mode = SM4.SM4_ENCRYPT;

			byte[] keyBytes;
			byte[] ivBytes;

			keyBytes = secretKey.getBytes();
			ivBytes = iv.getBytes();

			SM4 sm4 = new SM4();
			sm4.sm4_setkey_enc(ctx, keyBytes);
			byte[] encrypted = sm4.sm4_crypt_cbc(ctx, ivBytes,
					plainText.getBytes("GBK"));
//			String cipherText = new BASE64Encoder().encode(encrypted);
			String cipherText = Base64.getEncoder().encodeToString(encrypted);
			if (cipherText != null && cipherText.trim().length() > 0) {
				Pattern p = Pattern.compile("\\s*|\t|\r|\n");
				Matcher m = p.matcher(cipherText);
				cipherText = m.replaceAll("");
			}
			return cipherText;
		
	}

	public String decryptData_CBC(String cipherText) throws Exception {
		
			SM4_Context ctx = new SM4_Context();
			ctx.isPadding = true;
			ctx.mode = SM4.SM4_DECRYPT;

			byte[] keyBytes;
			byte[] ivBytes;

			keyBytes = secretKey.getBytes();
			ivBytes = iv.getBytes();

			SM4 sm4 = new SM4();
			sm4.sm4_setkey_dec(ctx, keyBytes);
//			byte[] decrypted = sm4.sm4_crypt_cbc(ctx, ivBytes, new BASE64Decoder().decodeBuffer(cipherText));
			byte[] decrypted = sm4.sm4_crypt_cbc(ctx, ivBytes, Base64.getDecoder().decode(cipherText));
			return new String(decrypted, "GBK");
		
	}

	public static void main(String[] args) throws Exception {
/*
{
"request": {
"zjlb": "01",
"zjhm": "F5D856E243D012B39366AAEA31DBF370F5794A338E09869C4B838687A086E11D",
"rzfs": "AB49758A0EAA8DC97FC2C68B3F442331" ,
"file1":"07749D1B30A120BB3A520D3BE56F8871",
"aan001": "959948487",
"qqsj": "88838FD60ED00611FAB71B1C0DB3F14D"
    }
}

{
"request": {
"zjlb": "AB49758A0EAA8DC97FC2C68B3F442331",
"zjhm": "FAA2DEAF554FEE017E210ED3EE3E3EB65D0D21B7F2D5CE51E3F155DEF5CB4F51",
"aan001": "959948487",
"reason":"sss"

    }
}
{
"request":{
"zjlb": "AB49758A0EAA8DC97FC2C68B3F442331",     
"zjhm": "F99275EE3942C1ED7D608C90D7A8C26DE685632F3D050C383F81CFB523D71CE1",
"aan001": "959948487",
"bglb": [
        {
"bgx": "913C52EE2584110656228CE26A1E05BC",
"bgqz": "AB49758A0EAA8DC97FC2C68B3F442331",
"bghz": "66C7EBAFC4FBC55EBC35AC5A468D6EE2"
        }
    ]
}
}
    {
"request":{
"zjlb": "AB49758A0EAA8DC97FC2C68B3F442331",     
"zjhm": "0D7E81E80FC1B7BFBA2FBEC3496418596F8EB1BA8020C174FE124D167A346B4C",
"aan001": "959948487",
"bglb": [
        {
"bgx": "913C52EE2584110656228CE26A1E05BC",
"bgqz": "AB49758A0EAA8DC97FC2C68B3F442331",
"bghz": "66C7EBAFC4FBC55EBC35AC5A468D6EE2"
        }
    ]
}
}


{
"request": {
"scsj": "88838FD60ED00611FAB71B1C0DB3F14D",
"zjlb": "AB49758A0EAA8DC97FC2C68B3F442331",     
"zjhm": "F99275EE3942C1ED7D608C90D7A8C26DE685632F3D050C383F81CFB523D71CE1",
"ewmbs": "21B5921CBF5DCB4E1A22E18144BDE519",
"aan001": "959948487"
    }
}


{
"request": {
"aan001": "959948487",
"business":"3F9550A0C81B13494BECC986BBB42638",
"dysj": " 88838FD60ED00611FAB71B1C0DB3F14D",
"ewmsg": "FAB01A9D933B48DC5BF6C6EE1619C5FE64DBD818D917FEDBCA2D9EDC30CBB058DD0C34F252AC35CBDBE731DBE1237645AF4EE4360889F0CCFBD6EEC88881C03C56CF088829097FDD8EC76B2C08569AA2"
    }
}

*/
		
		
		String plainText = "123456";
		// QPu83ZF0jbzISutCBEAy3zHGrApNe5mkaCRSMqEe4H4=

		SM4Utils sm4 = new SM4Utils();
		sm4.secretKey = "JeF8U9wHFOMfs2Y8";
		// sm4.secretKey = "QPu83ZF0jbzISutCBEAy3zHGrApNe5mkaCRSMqEe4H4=";
		sm4.hexString = false;

		System.out.println("ECB模式");
		String cipherText = sm4.encryptData_ECB(plainText);
		System.out.println("密文: " + cipherText);
		System.out.println(cipherText.length());

		plainText = sm4.decryptData_ECB(cipherText);
		System.out.println("明文: " + plainText);
		System.out.println("");

/*
ECB模式
密文: ECF36E17304FBCD1470CA957063AA164
32
明文: 123456
*/

	}
}
